package com.hzhk.happyrent.utils;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;


import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.hzhk.happyrent.App;
import com.hzhk.happyrent.Constants;
import com.hzhk.happyrent.bean.login.LoginResponse;
import com.hzhk.happyrent.bean.rent.BaseModel;
import com.hzhk.happyrent.bean.rent.ProductListModel;
import com.hzhk.happyrent.bean.rent.ProductListNewsBean;
import com.hzhk.happyrent.bean.rent.RentHeaderPagerBean;
import com.hzhk.happyrent.bean.rent.TypesModel;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class MyPerference {

	private static final String FILE_NAME = "maitian_preferences";
	private static String defauleUid = "";

	private static MyPerference mp;

	private static boolean firstIn = true;

	private static String userId;
	private static String userPhone;
	private static String iconUrl;
	private static String passWord;
	private static String auth;
	private static String personInfo;





	public String getPersonInfo() {
		if (!StringUtils.isEmpty(personInfo)) {
			return personInfo;
		}
		personInfo = mp.getString(Constants.PERSON_INFO, "");
		return personInfo;
	}

	public void setPersonInfo(String personInfo) {
		mp.saveString(Constants.PERSON_INFO,personInfo);
		mp.personInfo = personInfo;
	}

	private static String deviceID;
	private static Boolean isFirst=true;


	public void setIsFirst(Boolean isFirst) {
		mp.saveBoolean(Constants.FIRSTIN,isFirst);
		mp.isFirst = isFirst;
	}

	public boolean getFirstIn() {
		return mp.getBoolean(Constants.FIRSTIN,isFirst);
	}


	public void setAuth(String defValue) {
		mp.saveString(Constants.IS_AUTH,defValue);
		mp.auth = defValue;
	}
	public String getAuth() {
		if (!StringUtils.isEmpty(mp.auth)) {
			return mp.auth;
		}
		mp.auth = mp.getString(Constants.IS_AUTH, "0");
		return mp.auth;
	}


	public static MyPerference getInstance() {
		if (null == mp)
			mp = new MyPerference(App.getContext());
		return mp;
	}

	public String getUserId() {
		if (!StringUtils.isEmpty(userId)) {
			return userId;
		}
		userId = mp.getString(Constants.USER_ID, defauleUid);
		return userId;
	}

	public void setUserId(String userId) {
		mp.userId = userId;
	}

	public String getUserPhone() {
		if (!StringUtils.isEmpty(userPhone)) {
			return userPhone;
		}
		userPhone = mp.getString(Constants.USER_PHONE, "");
		return userPhone;
	}

	public void setUserPhone(String userPhone) {
		MyPerference.userPhone = userPhone;
	}



	public String getPassWord() {
		if (!StringUtils.isEmpty(passWord)) {
			return passWord;
		}
		passWord = mp.getString(Constants.USER_PASS, "");
		return passWord;
	}

	public void setPassWord(String passWord) {
		mp.passWord = passWord;
	}



	public void setUserInfo(MyPerference mp) {
		setUserId(mp.getString(Constants.USER_ID, defauleUid));
		setUserPhone(mp.getString(Constants.USER_PHONE, null));
		setPassWord(mp.getString(Constants.USER_PASS, null));
	}

	/**
	 * 清除所有用户信息
	 * 
	 * @param
	 */
	public void clearUserInfo() {
		mp.saveString(Constants.USER_ID, null);
		mp.saveString(Constants.USER_PHONE, null);
		mp.saveString(Constants.USER_PASS, null);

		setUserId(mp.getString(Constants.USER_ID, defauleUid));
		setUserPhone(mp.getString(Constants.USER_PHONE, null));
		setPassWord(mp.getString(Constants.USER_PASS, null));
	}


	public<T> void setUserInfo(Class<T> c, String mess) {
		mp.saveString(c.getClass().getName(), mess);
	}
	public<T> T getUserInfo(Class<T> c) {

		String mess=mp.getString(c.getClass().getName(),null);
		if(!TextUtils.isEmpty(mess)){
			T t=new Gson().fromJson(mess,c);
			return t;
		}
		return null;
	}

	/**
	 * 用户登录信息添加
	 * 
	 */
	public void setUserInfoSave(String id,String userPhone,
                                       String userpwd,String auth) {
		if (mp == null) {
			mp = new MyPerference(App.getContext());
		}
		mp.saveString(Constants.USER_ID, id);
		mp.saveString(Constants.USER_PHONE, userPhone);
		mp.saveString(Constants.USER_PASS, userpwd);
		mp.saveString(Constants.IS_AUTH, auth);

		setUserId(id);
		setUserPhone(userPhone);
		setPassWord(userpwd);
		setAuth(auth);
	}
	protected SharedPreferences settings;
	protected SharedPreferences.Editor editor;

	public MyPerference(Context context) {
		try {
			settings = context.getSharedPreferences(FILE_NAME,
					Context.MODE_PRIVATE);
			editor = settings.edit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 保存List
	 *
	 * @param key      sp key值
	 * @param datalist list
	 * @param <T>      item 类型
	 */
	public  <T> void setDataList(String key, List<T> datalist) {
		if (null == datalist || datalist.size() <= 0)
			return;

		Gson gson = new Gson();
		//转换成json数据，再保存
		String strJson = gson.toJson(datalist);
		mp.saveString(key, strJson);
	}

	/**
	 * 获取List
	 *
	 * @param key sp key值
	 * @param <T> item 类型
	 * @return list
	 */
	public <T> List<T> getDataList(String key, Class<T> cls) {
		Class[] forment=new Class[]{RentHeaderPagerBean.class
				, TypesModel.class
				, ProductListModel.class
				, ProductListNewsBean.class};
		List<T> datalist = new ArrayList<T>();
		String strJson = mp.getString(key, null);

		if (null == strJson) {
			return datalist;
		}

		try {
			Gson gson = new Gson();
			//        datalist = gson.fromJson(strJson, new TypeToken<List<T>>(){}.getType());
			JsonArray array = new JsonParser().parse(strJson).getAsJsonArray();
//			for (final JsonElement elem : array) {
//				datalist.add(gson.fromJson(elem, cls));
//			}
			for (int i = 0; i < array.size(); i++) {
				datalist.add((T) gson.fromJson(array.get(i), forment[i]));
			}
		}catch (Exception e){
			e.printStackTrace();
		}

		return datalist;
	}

	// 保存数组
	private void saveArray(String key, int[] value) {
		editor.putString(key, value.toString());
		editor.commit();
	}

	// 获取数组
	private int[] getArray(String key, int arrayLength) {
		int[] resArray = new int[arrayLength];
		Arrays.fill(resArray, -1);
		try {
			JSONArray jsonArray = new JSONArray(settings.getString(key, "[]"));
			for (int i = 0; i < jsonArray.length(); i++) {
				resArray[i] = jsonArray.getInt(i);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resArray;
	}

	private void saveBoolean(String key, boolean value) {
		editor.putBoolean(key, value);
		editor.commit();
	}

	private void saveFloat(String key, float value) {
		editor.putFloat(key, value);
		editor.commit();
	}

	private void saveInt(String key, int value) {
		editor.putInt(key, value);
		editor.commit();
	}

	private void saveLong(String key, long value) {
		editor.putLong(key, value);
		editor.commit();
	}

	public void saveString(String key, String value) {
		if (Constants.USER_ID.equals(key)) {
			setUserId(value);
		}
		editor.putString(key, value);
		editor.commit();
	}
	private void save(String key, String value) {
		editor.putString(key, value);
		editor.commit();
	}
	private void saveStringSet(String key, HashSet<String> value) {
		editor.putStringSet(key, value);
		editor.commit();
	}
	private Set<String> getSetString(String key, HashSet<String> defValue) {
		return settings.getStringSet(key, defValue);
	}
	private void clear(String key) {
		editor.remove(key);
		editor.commit();
	}

	private void clear() {
		editor.clear();
		editor.commit();
	}

	private boolean getBoolean(String key, boolean defValue) {
		return settings.getBoolean(key, defValue);
	}

	private float getFloat(String key, float defValue) {
		return settings.getFloat(key, defValue);
	}

	private int getInt(String key, int defValue) {
		return settings.getInt(key, defValue);
	}

	private long getLong(String key, long defValue) {
		return settings.getLong(key, defValue);
	}

	public String getString(String key, String defValue) {
		return settings.getString(key, defValue);
	}
}
